﻿<%@ WebHandler Language="C#" Class="InputCheckItemFormHandler" %>

/*Description: 新实测值录入（报工、检验）
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer: Zhangrj 
'create Date:20221216
'Rewriter:
'Rewrite Date:
*/
using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Configuration;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using NPOI.SS.UserModel;
using System.Text.RegularExpressions;

public class InputCheckItemFormHandler : IHttpHandler, IRequiresSessionState
{

    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness m_CommonObj = new uLMSCommonBusiness();
    uLMSStepCheckPointIBusiness m_CheckPointObj = uMESBusinessFactory.instance.GetuLMSStepCheckPointObject();
    string usingImg = ConfigurationManager.AppSettings["UsingCheckImageSavePath"];
    bool isUseIP = ConfigurationManager.AppSettings["IsUseIP"] == "1" ? true : false;
    string importPath = ConfigurationManager.AppSettings["ImportPath"]; //导入路径
    string exportPath = ConfigurationManager.AppSettings["ExportPath"]; //导出路径
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            var url = context.Request.UrlReferrer.Query.ToString();
            if (url.IndexOf("isVue3") != -1)
            {
                Match match = Regex.Match(url, @"employeename=(.*?)(?:&|$)");
                if (match.Success)
                {
                    string employeename = match.Groups[1].Value;
                    m_UserInfo = m_CommonObj.GetUserInfo(employeename, "");
                }
            }
            else
            {
                m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            }

            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "数据过期，请重新登录" }));
                return;
            }
            switch (action)
            {
                case "InitCheckPointPageByReport"://初始化实测值录入页面（报工）
                    InitCheckPointPageByReport(context);
                    break;
                case "InitCheckPointPageByCheck"://初始化检验实测值页面（检验）
                    InitCheckPointPageByCheck(context);
                    break;
                case "GetStepCheckPointData"://获取检测项列表
                    GetStepCheckPointData(context);
                    break;
                case "GetStepCheckPointResult"://获取检测项结果列表
                    GetStepCheckPointResult(context);
                    break;
                case "GetUnInputChildContainer"://获取未录入子序号
                    GetUnInputChildContainer(context);
                    break;
                case "SaveCheckResultByWorker"://保存实测值（工人）
                    SaveCheckResultByWorker(context);
                    break;
                case "DeleteCheckPointResult"://删除实测值
                    DeleteCheckPointResult(context);
                    break;
                case "ExportCheckPointFileByWorker"://导出实测值（工人）
                    ExportCheckPointFileByWorker(context);
                    break;
                case "ImportCheckPointFileByWorker"://导入实测值（工人）
                    ImportCheckPointFileByWorker(context);
                    break;
                case "SaveCheckResultByCheck"://保存实测值（检验）
                    SaveCheckResultByCheck(context);
                    break;
                case "SaveAllCheckResultByCheck"://一键确认保存实测值（检验）
                    SaveAllCheckResultByCheck(context);
                    break;
                case "ExportCheckPointFileByCheck"://导出实测值（检验）
                    ExportCheckPointFileByCheck(context);
                    break;
                case "ImportCheckPointFileByCheck"://导入实测值（检验）
                    ImportCheckPointFileByCheck(context);
                    break;
                case "SaveCheckPointResultDocFile"://保存实测值的附件
                    SaveCheckPointResultDocFile(context);
                    break;
                case "SaveSendThreeCoordinateRecord"://保存推送给三坐标检测记录
                    SaveSendThreeCoordinateRecord(context);
                    break;
                case "GetResultDocFile"://下载附件（暂时弃用）
                    GetResultDocFile(context);
                    break;
                case "IsValidCheckPointResult"://验证实测值是否超差
                    IsValidCheckPointResult(context);
                    break;
                case "IsValidCheckPointResultByOnKey"://验证实测值是否超差（检验一键确认）
                    IsValidCheckPointResultByOnKey(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            uMESProcessResult result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }
    /// <summary>
    /// 验证实测值是否超差（通过检测项）
    /// </summary>
    public void IsValidCheckPointResult(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string strCode = GetCode(context);//实测值;
        DataTable dtStepCheckPoint = JsonConvert.DeserializeObject<DataTable>(context.Request["stepCheckPointData"].ToString());//检测项列表
        foreach (DataRow item in dtStepCheckPoint.Rows)
        {
            if (IsOverproofResult(item["basevalue"].ToString(), item["floorfloat"].ToString(), item["ceilfloat"].ToString(), strCode))
            {
                result.Result = false;
                result.Message += string.Format("{0}，", item["bubblenumber"].ToString());
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 验证实测值是否超差（检验一键确认）
    /// </summary>
    public void IsValidCheckPointResultByOnKey(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string containerID = context.Request["containerId"].ToString();//批次ID
        string containerStepWorkReportID = context.Request["containerStepWorkReportID"].ToString();//报工ID
        //更新数据
        string sql = string.Format(@"SELECT nvl(sp.checkpointresultnotedis,sp.workcheckpointresultnotedis) checkpointresult,st.basevalue,st.floorfloat,st.ceilfloat,st.bubblenumber
                                    FROM stepcheckpointresult sp
                                    LEFT JOIN stepcheckpoint st ON st.stepcheckpointid = sp.stepcheckpointid
                                    WHERE sp.containerid = '{0}' AND sp.containerstepworkreportid = '{1}'",
                                    containerID, containerStepWorkReportID);
        DataTable dtStepCheckPoint = DatabaseHelper.Query_ReturnDatTable(sql);//检测项列表
        foreach (DataRow item in dtStepCheckPoint.Rows)
        {
            if (IsOverproofResult(item["basevalue"].ToString(), item["floorfloat"].ToString(), item["ceilfloat"].ToString(), item["checkpointresult"].ToString()))
            {
                result.Result = false;
                result.Message += string.Format("{0}，", item["bubblenumber"].ToString());
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 验证实测值是否超差
    /// </summary>
    /// <param name="baseValueStr"></param>
    /// <param name="floorFloatStr"></param>
    /// <param name="ceilFloatStr"></param>
    /// <param name="resValueStr"></param>
    /// <returns></returns>
    private bool IsOverproofResult(string baseValueStr, string floorFloatStr, string ceilFloatStr, string resValueStr)
    {
        double resCode = 0;//转换后的实测值
        double baseValue = 0, floorfloat = 0, ceilfloat = 0;//基准值，下浮动，上浮动
        if (string.IsNullOrWhiteSpace(resValueStr) || !double.TryParse(resValueStr.Trim(), out resCode)) //如果实测值不是数值类型，则不验证
        {
            return false;
        }
        if (string.IsNullOrWhiteSpace(baseValueStr) || !double.TryParse(baseValueStr.Trim(), out baseValue))
        {
            return false;
        }
        if (string.IsNullOrWhiteSpace(ceilFloatStr) || !double.TryParse(ceilFloatStr.Trim(), out ceilfloat))
        {
            return false;
        }
        if (string.IsNullOrWhiteSpace(floorFloatStr) || !double.TryParse(floorFloatStr.Trim(), out floorfloat))
        {
            return false;
        }
        if (resCode > (baseValue + ceilfloat) || resCode < (baseValue + floorfloat)) //如果大于上浮动，或者小于下浮动，则超差
        {
            return true;
        }
        return false;
    }

    /// <summary>
    /// 保存推送给三坐标检测记录
    /// </summary>
    /// <param name="context"></param>
    public void SaveSendThreeCoordinateRecord(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable dtCheckPoint = JsonConvert.DeserializeObject<DataTable>(context.Request["checkPoint"].ToString());
        Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["mainParam"].ToString());
        if (dtCheckPoint.Rows.Count == 0 || string.IsNullOrWhiteSpace(dic["CONTAINERNAME"]))
        {
            result.Result = false; result.Message = "未选择数据";
            goto L1;
        }
        //验证是否已有记录数据
        string stepCheckPointIDs = string.Empty;
        List<Dictionary<string, object>> checkPointIDList = new List<Dictionary<string, object>>();
        dtCheckPoint.AsEnumerable().ToList().ForEach(p =>
        {
            stepCheckPointIDs += string.Format("'{0}',", p["StepCheckPointID"].ToString());
            checkPointIDList.Add(new Dictionary<string, object> { { "stepCheckPointId", p["StepCheckPointID"].ToString() } });
        });
        stepCheckPointIDs = stepCheckPointIDs.Trim(',');
        string sql = string.Format("SELECT 1 FROM SendThreeCoordinateRecord s WHERE s.stepcheckpointid IN ({0})", stepCheckPointIDs);
        if (DatabaseHelper.GetSingle(sql) != null)
        {
            result.Result = false; result.Message = "已存在相同的检测项";
            goto L1;
        }
        //查询派工记录
        if (dic.ContainsKey("CONTAINERSTEPDISPATCHID"))
        {
            sql = string.Format("SELECT csd.qty,csd.containerstepdispatchid FROM containerstepdispatch csd WHERE csd.containerstepdispatchid = '{0}'", dic["CONTAINERSTEPDISPATCHID"]);
        }
        else
        {
            //如果不包含派工ID，则通过报工ID来查询（主要针对检验录入）
            sql = string.Format(@"SELECT csw.qty,csd.containerstepdispatchid FROM containerstepworkreport csw
            LEFT JOIN containerstepdispatch csd ON csd.containerstepdispatchid = csw.containerstepdispatchid
            WHERE csw.containerstepworkreportid = '{0}'", dic["CONTAINERSTEPWORKREPORTID"]);
        }
        DataTable dtDis = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtDis.Rows.Count == 0)
        {
            result.Result = false; result.Message = "未找到对应的派工数据";
            goto L1;
        }
        if (!m_CheckPointObj.UpdateStepCheckPointValue(checkPointIDList))//调用更新基准值方法
        {
            result.Result = false; result.Message = "更新基准值失败";
            goto L1;
        }
        List<ExcuteEntity> insertList = new List<ExcuteEntity>();
        string id2 = Guid.NewGuid().ToString();
        foreach (DataRow item in dtCheckPoint.Rows)
        {
            //插入数据库
            ExcuteEntity exuteEntity = new ExcuteEntity("SendThreeCoordinateRecord", ExcuteEntity.ExcuteTypeEnum.insert);
            List<FieldEntity> excuteFieldList = new List<FieldEntity>();
            excuteFieldList.Add(new FieldEntity("Id", Guid.NewGuid().ToString(), FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("Id2", id2, FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("Containerid", dic["CONTAINERID"], FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("Workflowstepid", dic["WORKFLOWSTEPID"], FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("Containername", dic["CONTAINERNAME"], FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("Workflowstepname", dic["WORKFLOWSTEPNAME"], FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("Containerstepdispatchid", dtDis.Rows[0]["CONTAINERSTEPDISPATCHID"].ToString(), FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("Stepcheckpointid", item["StepCheckPointID"].ToString(), FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("CreateEmployeeId", m_UserInfo.EmployeeID, FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("CreateDate", DateTime.Now, FieldEntity.FieldTypeEnum.DateTime));
            excuteFieldList.Add(new FieldEntity("ApplyFactoryCode", m_UserInfo.FactoryCode, FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("IsSend", "0", FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("IsUse", "0", FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("Qty", int.Parse(dtDis.Rows[0]["QTY"].ToString()), FieldEntity.FieldTypeEnum.Numer));
            excuteFieldList.Add(new FieldEntity("FactoryID", m_UserInfo.FactoryID, FieldEntity.FieldTypeEnum.Str));
            exuteEntity.ExcuteFileds = excuteFieldList;
            insertList.Add(exuteEntity);
        }
        result.Result = DatabaseHelper.ExecuteDataByEntitys(insertList);
        result.Message = result.Result ? "保存成功" : "保存失败";
    L1: context.Response.Write(JsonConvert.SerializeObject(result));
    }

    public void GetResultDocFile(HttpContext context)
    {
        string resultDocPath = context.Request["resultDocPath"].ToString();
        string filePath = context.Server.MapPath(resultDocPath);
        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        byte[] bt = new byte[fs.Length];
        fs.Read(bt, 0, (int)fs.Length);
        var Response = HttpContext.Current.Response;
        Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlPathEncode(Path.GetFileNameWithoutExtension(filePath)));
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
        Response.ContentType = "application/octet-stream";
        Response.BinaryWrite(bt);

        Response.Flush();
        Response.End();
        Response.Close();

        //System.Diagnostics.Process proc = System.Diagnostics.Process.Start("chrome.exe", filePath);

        context.Response.Write(JsonConvert.SerializeObject(Response));
    }

    /// <summary>
    /// 获取未录入或全部的子序号
    /// </summary>
    /// <param name="context"></param>
    public void GetUnInputChildContainer(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string containerID = context.Request["containerId"].ToString();
        string stepCheckPointId = context.Request["stepCheckPointId"].ToString();
        bool isUnInput = bool.Parse(context.Request["isUnInput"].ToString());
        string sql = @"SELECT DISTINCT c.containerid,c.containername,c.parentcontainerid FROM container c 
LEFT JOIN stepcheckpointresult spr ON spr.childcontainerid = c.containerid AND spr.stepcheckpointid = '{1}'
WHERE c.parentcontainerid = '{0}' AND c.status = 1 ";
        if (isUnInput)
        {
            sql += " AND spr.stepcheckpointresultid IS NULL";
        }
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, containerID, stepCheckPointId));
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// //导入实测值（检验）
    /// </summary>
    /// <param name="context"></param>
    public void ImportCheckPointFileByCheck(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "导入成功" };
        string filePath = "";
        try
        {
            var files = context.Request.Files;
            HttpPostedFile file = files.Count > 1 ? files[files.Count - 1] : files[0];
            string IsXls = Path.GetExtension(file.FileName);
            if (IsXls != ".xls" && IsXls != ".xlsx")
            {
                result.Result = false; result.Message = "请上传EXCEL文件";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            string fileName = Path.GetFileNameWithoutExtension(file.FileName) + DateTime.Now.ToString("yyyyMMddHHmmssffff") + IsXls;
            string fileBasePath = importPath + "CheckItemTem/";
            if (!Directory.Exists(context.Server.MapPath(fileBasePath))) //如果没有目录，创建
            {
                Directory.CreateDirectory(context.Server.MapPath(fileBasePath));
            }
            filePath = context.Server.MapPath(fileBasePath + fileName);
            file.SaveAs(filePath);//保存文件

            IWorkbook workbook = uLMS_CommonFunction.GetWorkbookObj(filePath);
            if (workbook == null)
            {
                result.Result = false; result.Message = "解析出错";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            DeleteUploadedFile(filePath); //删除上传的文件
            DataTable dt = new DataTable();
            dt = uLMS_CommonFunction.ExcelImportToDataTable(workbook);
            ExcuteEntity exuteEntity = new ExcuteEntity("stepcheckpointresult", ExcuteEntity.ExcuteTypeEnum.selectAll);
            exuteEntity.WhereFileds = new List<FieldEntity>() { new FieldEntity("containerid", dt.Rows[0]["ContainerID"].ToString(), FieldEntity.FieldTypeEnum.Str) };
            DataTable dtContainerResult = DatabaseHelper.QueryDataByEntity(exuteEntity);//(new ExcuteEntity("stepcheckpointresult", ExcuteEntity.ExcuteTypeEnum.selectAll));
            string sqlContainer = "SELECT c.containername,c.containertype FROM containercurrentinfo c WHERE c.containerid = '{0}'";
            DataTable dtContainer = new DataTable();
            DataTable dtChildContainer = new DataTable();
            //填写检测项
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow row = dt.Rows[i];
                string strCode = row["检验实测值"].ToString(); //检验实测值
                string stepCheckPointID = row["StepCheckPointID"].ToString(); //检测项ID
                string containerName = row["流水卡"].ToString(); //流水卡
                string containerID = row["ContainerID"].ToString();
                string stepInfoID = row["StepInfoID"].ToString();
                string containerStepWorkReportID = row["ContainerStepWorkReportID"].ToString(); //报工ID
                dtContainer = DatabaseHelper.Query_ReturnDatTable(string.Format(sqlContainer, containerID));
                //判断是否有报工
                if (string.IsNullOrWhiteSpace(containerStepWorkReportID))
                {
                    result.Message = string.Format("导入成功：{0}条，第{1}行ContainerStepWorkReportID为空", (i).ToString(), (i + 1).ToString());
                    break;
                }
                //判断是否有该批次
                if (string.IsNullOrWhiteSpace(containerID) || dtContainer.Rows.Count == 0)
                {
                    result.Message = string.Format("导入成功：{0}条，第{1}行批次未找到", (i).ToString(), (i + 1).ToString());
                    break;
                }
                string childContainerID = row["ChildContainerID"].ToString(); //子序号ID
                dtChildContainer = m_CommonObj.GetContainerInfoByPerContianerID2(containerID);
                //如果未找到子序号ID，则结束
                if (dtContainer.Rows[0]["containertype"].ToString() == "3" && !dt.Columns.Contains("工步") && (string.IsNullOrWhiteSpace(childContainerID) || dtChildContainer.AsEnumerable().Where(p => p["containerid"].ToString() == childContainerID).Count() == 0))
                {
                    result.Message = string.Format("导入成功：{0}条，第{1}行的子批次为空或未找到", (i).ToString(), (i + 1).ToString());
                    break;
                }
                //判断工步
                if (dt.Columns.Contains("工步") && string.IsNullOrWhiteSpace(stepInfoID))
                {
                    result.Message = string.Format("导入成功：{0}条，第{1}行工步未找到", (i).ToString(), (i + 1).ToString());
                    break;
                }
                Dictionary<string, string> para = new Dictionary<string, string>();
                para.Add("ContainerID", containerID);
                para.Add("FactoryID", m_UserInfo.FactoryID);
                para.Add("StepCheckPointID", stepCheckPointID);
                para.Add("ChildContainerID", childContainerID);
                //para.Add("UsingImgPath", usingImg)
                para.Add("ContainerStepWorkReportID", containerStepWorkReportID);
                para.Add("StepInfoID", stepInfoID);
                para.Add("CheckerID", m_UserInfo.EmployeeID.ToString()); //检验员id
                para.Add("CheckPointResultNote", strCode); //检验值源码
                para.Add("CheckPointResultNoteDis", strCode); //检验值
                para.Add("StepCheckPointResultID", null); //结果ID
                //查询是否存在检测结果
                string selectStr = string.Format("stepcheckpointid='{0}' and containerstepworkreportid='{1}'", stepCheckPointID, containerStepWorkReportID);
                if (!string.IsNullOrWhiteSpace(childContainerID))
                {
                    selectStr += " and childcontainerid='" + childContainerID + "'";
                }
                DataRow[] drs = dtContainerResult.Select(selectStr);
                if (drs.Length > 0) //存在，则更新结果ID
                {
                    para["StepCheckPointResultID"] = drs[0]["stepcheckpointresultid"].ToString();
                    para["CheckResultDocPath"] = drs[0]["checkresultdocpath"].ToString();
                    if (string.IsNullOrWhiteSpace(para["CheckResultDocPath"]))
                    {
                        para["CheckResultDocPath"] = drs[0]["workresultdocpath"].ToString(); //将工人附件赋值给检验附件
                    }
                }

                //保存数据
                string msg = "";
                if (!(m_CheckPointObj.SaveCheckResultByCheck(para)))
                {
                    result.Message = string.Format("导入成功：{0}条，第{1}行数据保存时报错：{2}", (i).ToString(), (i + 1).ToString(), msg);
                    break;
                }
            }
        }
        catch (Exception ex)
        {
            DeleteUploadedFile(filePath);
            result.Result = false;
            result.Message = "上传失败：" + ex.Message;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 导出实测值（检验）
    /// </summary>
    /// <param name="context"></param>
    public void ExportCheckPointFileByCheck(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "导出成功" };
        try
        {
            DataTable dtContainer = JsonConvert.DeserializeObject<DataTable>(context.Request["container"].ToString());
            DataTable dtChildContainer = JsonConvert.DeserializeObject<DataTable>(context.Request["childContainer"].ToString());
            if (dtContainer.Rows.Count == 0)
            {
                result.Result = false; result.Message = "请选择批次";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            DataRow activeContainer = dtContainer.Rows[0];
            int[] picCol = new int[] { 8, 13 }; //需要填充图片的列 'update:wangjh 9,14->8,13
            string containerID = activeContainer["containerid"].ToString();
            string stepInfoName = activeContainer["StepInfoName"].ToString(); //工步名
            string stepInfoID = activeContainer["StepInfoID"].ToString(); //工步ID
            string containerName = activeContainer["ContainerName"].ToString(); //批次名
            string workflowStepName = activeContainer["Workflowstepname"].ToString(); //工序
            string containerStepWorkReportID = activeContainer["ContainerStepWorkReportID"].ToString();
            string workerName = activeContainer["FullName"].ToString(); //报工人
            string workQty = activeContainer["Qty"].ToString(); //报工数量
            Dictionary<string, string> oQuery = new Dictionary<string, string>();
            oQuery.Add("ContainerID", containerID);
            oQuery.Add("StepID", activeContainer["WorkFlowStepId"].ToString());
            oQuery.Add("ContainerStepWorkReportID", containerStepWorkReportID);
            if (!string.IsNullOrWhiteSpace(stepInfoID)) //如果包含工步，则添加
            {
                oQuery.Add("StepInfoID", stepInfoID);
                picCol = new[] { 9, 10, 15 }; //update:Wangjh 10, 11, 16->9, 10, 15
            }
            uMESProcessResult oResult = m_CheckPointObj.GetInputStepCheckPointList(oQuery); //获取该工步下的检测项
            DataTable checkPoint = oResult.DBTable;
            DataTable exDt = new DataTable(); //导出数据表
            exDt.Columns.Add("StepCheckPointID"); //检测项ID
            exDt.Columns.Add("ContainerID"); //批次ID
            exDt.Columns.Add("ChildContainerID"); //子序号ID
            exDt.Columns.Add("StepInfoID"); //工步ID
            exDt.Columns.Add("ContainerStepWorkReportID"); //检测项ID
            exDt.Columns.Add("流水卡"); //批次名
            exDt.Columns.Add("流水卡子序号"); //子序号
            exDt.Columns.Add("工序"); //工序
            if (!string.IsNullOrWhiteSpace(stepInfoID))
            {
                exDt.Columns.Add("工步"); //工步名
                exDt.Columns.Add("图纸要求"); //图纸要求
            }
            //exDt.Columns.Add("OriCheckPointNote") '检测项内容
            exDt.Columns.Add("检测项内容"); //生成一张图片后的检测项内容
            exDt.Columns.Add("检测类型"); //检测类型
            exDt.Columns.Add("关键特性标识"); //关键特性标识
            exDt.Columns.Add("报工人"); //报工人
            exDt.Columns.Add("报工数量"); //报工数量
            //exDt.Columns.Add("OriWorkCheckPointResultNote") '工人实测值
            exDt.Columns.Add("工人实测值"); //工人实测值
            exDt.Columns.Add("检验实测值"); //检验实测值
            List<object> para = new List<object>();
            //带子序号的
            if (dtChildContainer.Rows.Count > 0)
            {
                DataTable checkItemDt = checkPoint.DefaultView.ToTable(true, "StepCheckPointID");
                foreach (DataRow checkItem in checkItemDt.Rows)
                {
                    foreach (DataRow cdr in dtChildContainer.Rows)
                    {
                        DataRow[] checkItemResult = checkPoint.Select("StepCheckPointID=\'" + checkItem["StepCheckPointID"].ToString() + "\' and childcontainerid=\'" + cdr["ContainerId"].ToString() + "\'");
                        DataRow dr = exDt.NewRow();
                        if (checkItemResult.Length > 0)
                        {
                            dr["StepCheckPointID"] = checkItemResult[0]["StepCheckPointID"].ToString();
                            dr["ContainerID"] = containerID;
                            dr["StepInfoID"] = stepInfoID;
                            dr["ChildContainerID"] = cdr["ContainerId"].ToString();
                            dr["ContainerStepWorkReportID"] = containerStepWorkReportID;
                            dr["关键特性标识"] = checkItemResult[0]["KEYCHECKNAME"].ToString();
                            dr["流水卡"] = containerName;
                            dr["工序"] = workflowStepName;
                            dr["流水卡子序号"] = cdr["ContainerName"].ToString();
                            //获取检测项
                            string checkPointNote = checkItemResult[0]["CheckPointNoteDis"].ToString();
                            if (string.IsNullOrWhiteSpace(checkPointNote))
                            {
                                checkPointNote = m_CheckPointObj.ConvertTohtml(checkItemResult[0]["CheckPointNote"].ToString(), usingImg, isUseIP);
                            }
                            dr["检测项内容"] = GetCheckPointNote(context, checkPointNote);
                            //工人检测项
                            string workCheckPointResultNote = checkItemResult[0]["WorkCheckPointResultNoteDis"].ToString();
                            if (string.IsNullOrWhiteSpace(System.Convert.ToString(workCheckPointResultNote)))
                            {
                                workCheckPointResultNote = m_CheckPointObj.ConvertTohtml(checkItemResult[0]["WorkCheckPointResultNote"].ToString(), usingImg, isUseIP);
                            }
                            dr["工人实测值"] = GetCheckPointNote(context, workCheckPointResultNote);
                            //工步
                            if (!string.IsNullOrWhiteSpace(stepInfoName))
                            {
                                string drawingrequire = checkItemResult[0]["drawingrequiredis"].ToString();
                                if (string.IsNullOrWhiteSpace(System.Convert.ToString(drawingrequire)))
                                {
                                    drawingrequire = checkItemResult[0]["drawingrequire"].ToString();
                                }
                                dr["图纸要求"] = GetCheckPointNote(context, drawingrequire);
                                dr["工步"] = stepInfoName;
                            }
                            dr["检测类型"] = checkItemResult[0]["CHECKTYPENAME"].ToString();
                            dr["报工人"] = workerName;
                            dr["报工数量"] = workQty;

                        }
                        else
                        {
                            checkItemResult = checkPoint.Select("StepCheckPointID=\'" + checkItem["StepCheckPointID"].ToString() + "\'");
                            dr["StepCheckPointID"] = checkItemResult[0]["StepCheckPointID"].ToString();
                            dr["ContainerID"] = containerID;
                            dr["ChildContainerID"] = cdr["ContainerId"].ToString();
                            dr["StepInfoID"] = stepInfoID;
                            dr["ContainerStepWorkReportID"] = containerStepWorkReportID;
                            dr["关键特性标识"] = checkItemResult[0]["KEYCHECKNAME"].ToString();
                            dr["流水卡"] = containerName;
                            dr["工序"] = workflowStepName;
                            dr["流水卡子序号"] = cdr["ContainerName"].ToString();
                            //获取检测项
                            string checkPointNote = checkItemResult[0]["CheckPointNoteDis"].ToString();
                            if (string.IsNullOrWhiteSpace(checkPointNote))
                            {
                                checkPointNote = m_CheckPointObj.ConvertTohtml(checkItemResult[0]["CheckPointNote"].ToString(), usingImg, isUseIP);
                            }
                            dr["检测项内容"] = GetCheckPointNote(context, checkPointNote);

                            dr["工人实测值"] = "";
                            //工步
                            if (!string.IsNullOrWhiteSpace(stepInfoName))
                            {
                                string drawingrequire = checkItemResult[0]["drawingrequiredis"].ToString();
                                if (string.IsNullOrWhiteSpace(System.Convert.ToString(drawingrequire)))
                                {
                                    drawingrequire = checkItemResult[0]["drawingrequire"].ToString();
                                }
                                dr["图纸要求"] = GetCheckPointNote(context, drawingrequire);
                                dr["工步"] = stepInfoName;
                            }
                            dr["检测类型"] = checkItemResult[0]["CHECKTYPENAME"].ToString();
                            dr["报工人"] = workerName;
                            dr["报工数量"] = workQty;
                        }
                        exDt.Rows.Add(dr);
                    }
                }
            }
            else //不带子序号
            {
                foreach (DataRow row in checkPoint.Rows)
                {
                    DataRow dr = exDt.NewRow();
                    dr["StepCheckPointID"] = row["StepCheckPointID"].ToString();
                    dr["ContainerID"] = containerID;
                    dr["ChildContainerID"] = "";
                    dr["StepInfoID"] = stepInfoID;
                    dr["ContainerStepWorkReportID"] = containerStepWorkReportID;
                    dr["关键特性标识"] = row["KEYCHECKNAME"].ToString();
                    dr["流水卡"] = containerName;
                    dr["工序"] = workflowStepName;
                    dr["流水卡子序号"] = "";
                    //获取检测项
                    string checkPointNote = row["CheckPointNoteDis"].ToString();
                    if (string.IsNullOrWhiteSpace(checkPointNote))
                    {
                        checkPointNote = m_CheckPointObj.ConvertTohtml(row["CheckPointNote"].ToString(), usingImg, isUseIP);
                    }
                    dr["检测项内容"] = GetCheckPointNote(context, checkPointNote);
                    //工人检测项
                    string workCheckPointResultNote = row["WorkCheckPointResultNoteDis"].ToString();
                    if (string.IsNullOrWhiteSpace(workCheckPointResultNote))
                    {
                        workCheckPointResultNote = m_CheckPointObj.ConvertTohtml(row["WorkCheckPointResultNote"].ToString(), usingImg, isUseIP);
                    }
                    dr["工人实测值"] = GetCheckPointNote(context, workCheckPointResultNote);
                    //工步
                    if (!string.IsNullOrWhiteSpace(stepInfoName))
                    {
                        string drawingrequire = row["drawingrequiredis"].ToString();
                        if (string.IsNullOrWhiteSpace(drawingrequire))
                        {
                            drawingrequire = row["drawingrequire"].ToString();
                        }
                        dr["图纸要求"] = GetCheckPointNote(context, drawingrequire);
                        dr["工步"] = stepInfoName;
                    }
                    dr["检测类型"] = row["CHECKTYPENAME"].ToString();
                    dr["报工人"] = workerName;
                    dr["报工数量"] = workQty;
                    exDt.Rows.Add(dr);
                }
            }
            //导出excel
            string fileName = "检验实测值导出(" + m_UserInfo.FullName + ")" + DateTime.Now.ToString("yyyyMMddHHmmddssffff") + ".xls";
            string strPath = context.Request.MapPath(exportPath + "CheckItemTem/");
            if (!Directory.Exists(strPath)) //如果没有目录，创建
            {
                Directory.CreateDirectory(strPath);
            }
            strPath += fileName;
            byte[] ms = uLMS_CommonFunction.DataTableExportToExcel(exDt, null, new int[] { 8, 13 });
            uLMS_CommonFunction.ParseBytesToFile(ms, strPath);
            string url = "http://" + context.Request.Url.Host + context.Request.ApplicationPath + exportPath.Trim('~').Replace("\\", "/") + "CheckItemTem/" + fileName;
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("filename", fileName);
            dic.Add("url", url);
            result.ReturnData = dic;
        }
        catch (Exception ex)
        {
            result.Message = "导出失败：" + ex.Message;
            result.Result = false;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 一键确认保存（检验）
    /// </summary>
    /// <param name="context"></param>
    public void SaveAllCheckResultByCheck(HttpContext context)
    {
        string containerID = context.Request["containerId"].ToString();//批次ID
        string containerStepWorkReportID = context.Request["containerStepWorkReportID"].ToString();//报工ID
        //更新数据
        string sql = string.Format(@"UPDATE stepcheckpointresult sp SET sp.checkpointresultnote = sp.workcheckpointresultnote,sp.checkpointresultnotedis_b = sp.workcheckpointresultnotedis_b,
                                    sp.checkpointresultnotedis = sp.workcheckpointresultnotedis,sp.checkerid = '{0}',sp.checkdate = SYSDATE,
                                    sp.lastchangedate = SYSDATE,sp.tempdealfail = 0
                                    WHERE sp.containerid = '{1}' AND sp.containerstepworkreportid = '{2}'
                                    AND sp.workcheckpointresultnotedis IS NOT NULL AND sp.checkpointresultnotedis IS NULL",
                                    m_UserInfo.EmployeeID.ToString(), containerID, containerStepWorkReportID);
        DatabaseHelper.ExecuteSql(sql);
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "一键确认成功" }));
    }
    /// <summary>
    /// 保存实测值（检验）
    /// </summary>
    /// <param name="context"></param>
    public void SaveCheckResultByCheck(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "保存成功" };
        DataTable dtChildContainer = JsonConvert.DeserializeObject<DataTable>(context.Request["childContainer"].ToString());
        DataTable dtCheckPointResult = JsonConvert.DeserializeObject<DataTable>(context.Request["checkPointResult"].ToString());
        string containerType = context.Request["containerType"].ToString();//批次类型
        //如果是子序号，则必须勾选子序号或者结果值
        if (containerType == "3" && dtChildContainer.Rows.Count == 0 && dtCheckPointResult.Rows.Count == 0)
        {
            result.Message = "请选择子序号或者结果值"; result.Result = false;
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        string strCode = GetCode(context);//检测值
        if (string.IsNullOrWhiteSpace(strCode) || strCode.Replace("\\", "/").Contains("/ImageTemp/"))
        {
            result.Result = false;
            result.Message = "未输入实测值或实测值无效";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        string stepCheckPointID = context.Request["stepCheckPointId"].ToString();//检测项ID
        string containerID = context.Request["containerId"].ToString();//批次ID
        string containerStepWorkReportID = context.Request["containerStepWorkReportID"].ToString();//报工ID
        Dictionary<string, string> oQuery = new Dictionary<string, string>();
        oQuery.Add("CheckerID", m_UserInfo.EmployeeID.ToString()); //检验员id
        oQuery.Add("CheckPointResultNote", strCode); //检验值源码
        oQuery.Add("CheckPointResultNoteDis", m_CheckPointObj.ConvertTohtml(strCode, usingImg, isUseIP)); //检验值
        oQuery.Add("FactoryID", m_UserInfo.FactoryID);
        oQuery.Add("ContainerStepWorkReportID", containerStepWorkReportID);
        oQuery.Add("StepCheckPointID", stepCheckPointID);
        oQuery.Add("UsingImgPath", usingImg);
        oQuery.Add("ContainerID", containerID);
        if (dtChildContainer.Rows.Count > 0 && dtCheckPointResult.Rows.Count == 0)//如果勾选了子序号，没有勾选结果
        {
            m_CheckPointObj.SaveCheckResultByCheck(oQuery, dtChildContainer);
        }
        else
        {
            //只要勾选了结果值，不管是否勾选子序号，都只更新勾选的结果值
            string sql = string.Format(@"SELECT sp.Stepcheckpointresultid,sp.workresultdocpath,sp.checkresultdocpath
                     FROM stepcheckpointresult sp 
                     WHERE sp.containerstepworkreportid = '{0}' AND sp.stepcheckpointid = '{1}'
                     AND sp.containerid = '{2}' ", containerStepWorkReportID, stepCheckPointID, containerID);
            if (dtCheckPointResult.Rows.Count > 0)
            {
                string checkPointResultIDs = string.Empty;
                dtCheckPointResult.AsEnumerable().ToList().ForEach(p => { checkPointResultIDs += string.Format("'{0}',", p["stepCheckPointResultID"].ToString()); });
                checkPointResultIDs = checkPointResultIDs.TrimEnd(',');
                sql += string.Format(" AND sp.Stepcheckpointresultid IN ({0})", checkPointResultIDs);
            }
            DataTable dtresult = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dtresult.Rows.Count > 0)
            {
                foreach (DataRow item in dtresult.Rows)
                {
                    oQuery.Add("StepCheckPointResultID", dtresult.Rows[0]["Stepcheckpointresultid"].ToString());
                    oQuery.Add("CheckResultDocPath", dtresult.Rows[0]["checkresultdocpath"].ToString());
                    if (string.IsNullOrWhiteSpace(oQuery["CheckResultDocPath"]))//如果检验没有上传附件，则改为工人上传的结果
                    {
                        oQuery["CheckResultDocPath"] = dtresult.Rows[0]["workresultdocpath"].ToString();//复制工人上传的附件
                    }
                    m_CheckPointObj.SaveCheckResultByCheck(oQuery);
                }
            }
            else
            {
                //没有结果值，则添加结果
                oQuery.Add("StepCheckPointResultID", null);
                oQuery.Add("CheckResultDocPath", "");
                oQuery.Add("ChildContainerID", "");
                m_CheckPointObj.SaveCheckResultByCheck(oQuery);
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 保存实测值的附件
    /// </summary>
    /// <param name="context"></param>
    public void SaveCheckPointResultDocFile(HttpContext context)
    {
        string fileComPath = "";
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "导入成功" };
        try
        {
            string uploadType = context.Request["uploadType"].ToString();
            DataTable dtStepCheckPointResult = JsonConvert.DeserializeObject<DataTable>(context.Request["checkPointResult"].ToString());//实测值结果
            if (dtStepCheckPointResult.Rows.Count == 0)
            {
                result.Message = "请选择实测值结果"; result.Result = false;
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }

            string docType = dtStepCheckPointResult.Rows[0]["docType"].ToString();
            if (string.IsNullOrWhiteSpace(docType))
            {
                result.Message = "请选择上传的文件类型"; result.Result = false;
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }

            var files = context.Request.Files;
            HttpPostedFile file = files.Count > 1 ? files[files.Count - 1] : files[0];
            string fileExtension = Path.GetExtension(file.FileName);
            string fileName = Path.GetFileNameWithoutExtension(file.FileName) + DateTime.Now.ToString("yyyyMMddHHmmssffff") + fileExtension;
            string filePath = "/UsingCheckImage/CheckResultDoc/";
            string fileBasePath = context.Server.MapPath(context.Request.ApplicationPath + filePath);
            if (!Directory.Exists(fileBasePath)) //如果没有目录，创建
            {
                Directory.CreateDirectory(fileBasePath);
            }
            fileComPath = fileBasePath + fileName;
            file.SaveAs(fileComPath);//保存文件
            //保存数据
            string docpath = uploadType == "1" ? "workresultdocpath" : "checkresultdocpath";
            string upLoadSql = "update stepcheckpointresult sp set sp.{0} = '{1}' where sp.stepcheckpointresultid = '{2}'";
            System.Collections.ArrayList list = new System.Collections.ArrayList();
            foreach (DataRow item in dtStepCheckPointResult.Rows)
            {
                //更新实测值结果表
                list.Add(string.Format(upLoadSql, docpath, filePath + fileName, item["stepcheckpointresultid"].ToString()));
            }
            if (list.Count > 0)
            {
                DatabaseHelper.ExecuteSqlTran(list);
            }
        }
        catch (Exception ex)
        {
            DeleteUploadedFile(fileComPath);
            result.Message = "上传出错，原因：" + ex.Message;
            result.Result = false;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 导入实测值
    /// </summary>
    /// <param name="context"></param>
    public void ImportCheckPointFileByWorker(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "导入成功" };
        string filePath = "";
        try
        {
            var files = context.Request.Files;
            HttpPostedFile file = files.Count > 1 ? files[files.Count - 1] : files[0];
            string IsXls = Path.GetExtension(file.FileName);
            if (IsXls != ".xls" && IsXls != ".xlsx")
            {
                result.Result = false; result.Message = "请上传EXCEL文件";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            string fileName = Path.GetFileNameWithoutExtension(file.FileName) + DateTime.Now.ToString("yyyyMMddHHmmssffff") + IsXls;
            string fileBasePath = importPath + "CheckItemTem/";
            if (!Directory.Exists(context.Server.MapPath(fileBasePath))) //如果没有目录，创建
            {
                Directory.CreateDirectory(context.Server.MapPath(fileBasePath));
            }
            filePath = context.Server.MapPath(fileBasePath + fileName);
            file.SaveAs(filePath);//保存文件

            IWorkbook workbook = uLMS_CommonFunction.GetWorkbookObj(filePath);
            if (workbook == null)
            {
                result.Result = false; result.Message = "解析出错";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            DeleteUploadedFile(filePath); //删除上传的文件
            DataTable dt = new DataTable();
            dt = uLMS_CommonFunction.ExcelImportToDataTable(workbook);
            string sqlContainer = "SELECT c.containername,c.containertype FROM containercurrentinfo c WHERE c.containerid = '{0}'";
            DataTable dtContainer = new DataTable();
            DataTable dtChildContainer = new DataTable();
            //填写检测项
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow row = dt.Rows[i];
                string containerID = row["ContainerID"].ToString();
                string stepInfoID = row["StepInfoID"].ToString();
                dtContainer = DatabaseHelper.Query_ReturnDatTable(string.Format(sqlContainer, containerID));
                //判断是否有该批次
                if (string.IsNullOrWhiteSpace(containerID) || dtContainer.Rows.Count == 0)
                {
                    result.Message = string.Format("导入成功：{0}条，第{1}行的批次为空或未找到", (i).ToString(), (i + 1).ToString());
                    break;
                }
                string childContainerID = row["ChildContainerID"].ToString(); //子序号ID
                dtChildContainer = m_CommonObj.GetContainerInfoByPerContianerID2(containerID);
                //如果未找到子序号ID，则结束
                if (dtContainer.Rows[0]["containertype"].ToString() == "3" && !dt.Columns.Contains("工步") && (string.IsNullOrWhiteSpace(childContainerID) || dtChildContainer.AsEnumerable().Where(p => p["containerid"].ToString() == childContainerID).Count() == 0))
                {
                    result.Message = string.Format("导入成功：{0}条，第{1}行的子批次为空或未找到", (i).ToString(), (i + 1).ToString());
                    break;
                }
                //如果未找到工步
                if (dt.Columns.Contains("工步") && string.IsNullOrWhiteSpace(stepInfoID))
                {
                    result.Message = string.Format("导入成功：{0}条，第{1}行的工步为空或未找到", (i).ToString(), (i + 1).ToString());
                    break;
                }
                Dictionary<string, string> para = new Dictionary<string, string>();
                para.Add("WORKERID", m_UserInfo.EmployeeID.ToString());
                para.Add("WORKCHECKPOINTRESULTNOTE", row["工人实测值"].ToString());
                para.Add("WORKCHECKPOINTRESULTNOTEDIS", row["工人实测值"].ToString());
                para.Add("ContainerID", containerID);
                para.Add("FactoryID", m_UserInfo.FactoryID);
                para.Add("StepCheckPointID", row["StepCheckPointID"].ToString());
                para.Add("ChildContainerID", childContainerID);
                //para.Add("UsingImgPath", usingImg)
                para.Add("StepInfoID", stepInfoID);
                //保存数据
                string msg = "";
                if (!(m_CheckPointObj.SaveCheckPointResultByImport(para, 1, ref msg)))
                {
                    result.Message = string.Format("导入成功：{0}条，第{1}行数据保存时报错", (i).ToString(), (i + 1).ToString());
                    break;
                }
            }
        }
        catch (Exception ex)
        {
            DeleteUploadedFile(filePath);
            result.Result = false;
            result.Message = "上传失败：" + ex.Message;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 导出检测值（工人）
    /// </summary>
    /// <param name="context"></param>
    public void ExportCheckPointFileByWorker(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "保存成功" };
        DataTable dtContainer = JsonConvert.DeserializeObject<DataTable>(context.Request["container"].ToString());//主批次
        DataTable dtChildContainer = JsonConvert.DeserializeObject<DataTable>(context.Request["childContainer"].ToString());//子序号批次
        int[] picCol = new int[] { 7 }; //需要填充图片的列,update:Wangjh 8->7
        string containerID = dtContainer.Rows[0]["ContainerID"].ToString();
        string stepInfoName = dtContainer.Rows[0]["StepInfoName"].ToString(); //工步名
        string stepInfoID = dtContainer.Rows[0]["StepInfoID"].ToString(); //工步ID
        string containerName = dtContainer.Rows[0]["ContainerName"].ToString(); //批次名
        string workflowStepName = dtContainer.Rows[0]["Workflowstepname"].ToString(); //工序
        DataTable exDt = new DataTable();
        exDt.Columns.Add("StepCheckPointID");//检测项ID
        exDt.Columns.Add("ContainerID");//批次ID
        exDt.Columns.Add("ChildContainerID");//子序号ID
        exDt.Columns.Add("StepInfoID");//工步ID
        exDt.Columns.Add("流水卡"); //批次名
        exDt.Columns.Add("流水卡子序号"); //子序号
        exDt.Columns.Add("工序");//工序
        if (!string.IsNullOrWhiteSpace(stepInfoName)) //如果有工步，则添加
        {
            exDt.Columns.Add("工步"); //工步名
            exDt.Columns.Add("图纸要求"); //图纸要求
            picCol = new[] { 8, 9 };
        }
        //exDt.Columns.Add("OriCheckPointNote") '要求值
        exDt.Columns.Add("检测项内容"); //导出后的要求值
        exDt.Columns.Add("检测类型"); //检测类型
        exDt.Columns.Add("关键特性标识"); //关键特性标识
        exDt.Columns.Add("工人实测值"); //工人实测值
        DataTable checkPoint = m_CheckPointObj.GetContainerCheckPointList(dtContainer.Rows[0]["workflowstepid"].ToString(), dtContainer.Rows[0]["StepInfoId"].ToString());
        List<object> para = new List<object>();
        if (dtChildContainer.Rows.Count > 0)
        {
            foreach (DataRow cdr in dtChildContainer.Rows)
            {
                foreach (DataRow row in checkPoint.Rows)
                {
                    DataRow dr = exDt.NewRow();
                    dr["StepCheckPointID"] = row["StepCheckPointID"];
                    dr["ContainerID"] = containerID;
                    dr["ChildContainerID"] = cdr["ContainerID"].ToString();
                    dr["StepInfoID"] = stepInfoID;
                    dr["关键特性标识"] = row["KeyCheckName"];
                    dr["流水卡"] = containerName;
                    dr["工序"] = workflowStepName;
                    dr["流水卡子序号"] = cdr["ContainerName"].ToString();
                    string checkPointNote = row["CheckPointNoteDis"].ToString();
                    //dr("OriCheckPointNote") = row("CheckPointNoteDis").ToString
                    if (string.IsNullOrWhiteSpace(checkPointNote))
                    {
                        checkPointNote = m_CheckPointObj.ConvertTohtml(row["CheckPointNote"].ToString(), usingImg, isUseIP);
                    }
                    dr["检测项内容"] = GetCheckPointNote(context, checkPointNote);
                    if (!string.IsNullOrWhiteSpace(stepInfoName)) //如果有工步，则添加
                    {
                        string drawingrequire = row["drawingrequiredis"].ToString();
                        if (string.IsNullOrWhiteSpace(drawingrequire))
                        {
                            drawingrequire = row["drawingrequire"].ToString();
                        }
                        dr["图纸要求"] = GetCheckPointNote(context, drawingrequire);
                        dr["工步"] = stepInfoName;
                    }
                    dr["检测类型"] = row["CheckTypeName"];
                    exDt.Rows.Add(dr);
                }
            }
        }
        else
        {
            foreach (DataRow row in checkPoint.Rows)
            {
                DataRow dr = exDt.NewRow();
                dr["StepCheckPointID"] = row["StepCheckPointID"];
                dr["ContainerID"] = containerID;
                dr["StepInfoID"] = stepInfoID;
                dr["ChildContainerID"] = "";
                dr["关键特性标识"] = row["KeyCheckName"];
                dr["流水卡"] = containerName;
                dr["工序"] = workflowStepName;
                dr["流水卡子序号"] = "";
                string checkPointNote = row["CheckPointNoteDis"].ToString();
                //dr("OriCheckPointNote") = row("CheckPointNoteDis").ToString
                if (string.IsNullOrWhiteSpace(checkPointNote))
                {
                    checkPointNote = m_CheckPointObj.ConvertTohtml(row["CheckPointNote"].ToString(), usingImg, isUseIP);
                }
                dr["检测项内容"] = GetCheckPointNote(context, checkPointNote);
                if (!string.IsNullOrWhiteSpace(stepInfoName)) //如果有工步，则添加
                {
                    string drawingrequire = row["drawingrequiredis"].ToString();
                    if (string.IsNullOrWhiteSpace(drawingrequire))
                    {
                        drawingrequire = row["drawingrequire"].ToString();
                    }
                    dr["图纸要求"] = GetCheckPointNote(context, drawingrequire);
                    dr["工步"] = stepInfoName;
                }
                dr["检测类型"] = row["CheckTypeName"];
                exDt.Rows.Add(dr);
            }
        }
        //导出excel
        string fileName = "工人实测值导出(" + m_UserInfo.FullName + ")" + DateTime.Now.ToString("yyyyMMddHHmmddssffff") + ".xls";
        string strPath = context.Request.MapPath(exportPath + "CheckItemTem/");
        if (!Directory.Exists(strPath)) //如果没有目录，创建
        {
            Directory.CreateDirectory(strPath);
        }
        strPath += fileName;
        byte[] ms = uLMS_CommonFunction.DataTableExportToExcel(exDt, null, picCol);

        uLMS_CommonFunction.ParseBytesToFile(ms, strPath);
        string url = "http://" + context.Request.Url.Host + context.Request.ApplicationPath + exportPath.Trim('~').Replace("\\", "/") + "CheckItemTem/" + fileName;
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("filename", fileName);
        dic.Add("url", url);
        result.ReturnData = dic;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取检测值
    /// </summary>
    /// <param name="context"></param>
    /// <param name="note"></param>
    /// <returns></returns>
    private string GetCheckPointNote(HttpContext context, string note)
    {
        uLMS_CommonFunction common = new uLMS_CommonFunction();
        if (note.Contains("<img"))
        {
            List<object> para = new List<object>();
            string[] sp = Regex.Split(note, "<img src=\"", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            foreach (string item in sp)
            {
                if (item.Contains("\\UsingCheckImage\\"))
                {
                    string[] sps = Regex.Split(item, "\">", RegexOptions.IgnoreCase);
                    string imgPath = context.Server.MapPath(sps[0]);
                    Bitmap bitmapImage = new Bitmap(imgPath);
                    para.Add(bitmapImage);
                    if (sps.Length > 1)
                    {
                        para.Add(sps[1]);
                    }
                }
                else
                {
                    para.Add(item);
                }
            }
            return common.MerageImagsAndStrs(para, 0);
        }
        return note;
    }
    /// <summary>
    /// 保存工人实测值
    /// </summary>
    /// <param name="context"></param>
    public void SaveCheckResultByWorker(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "保存成功" };
        string strCode = GetCode(context);//检测值
        if (string.IsNullOrWhiteSpace(strCode) || strCode.Replace("\\", "/").Contains("/ImageTemp/"))
        {
            result.Result = false;
            result.Message = "未输入实测值或实测值无效";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        string containerID = context.Request["containerId"].ToString();//批次ID
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("WORKERID", m_UserInfo.EmployeeID.ToString());
        dic.Add("WORKCHECKPOINTRESULTNOTE", strCode);
        dic.Add("WORKCHECKPOINTRESULTNOTEDIS", m_CheckPointObj.ConvertTohtml(strCode, usingImg, isUseIP));
        dic.Add("ContainerID", containerID);
        dic.Add("ChildContainerID", "");
        dic.Add("FactoryID", m_UserInfo.FactoryID);
        dic.Add("IsBatch", "1");//可批量添加结果值
        //处理数据
        string type = context.Request["type"].ToString();//操作类型
        switch (type)
        {
            case "add"://新增
                DataTable dtChildContainer = JsonConvert.DeserializeObject<DataTable>(context.Request["childContainer"].ToString());
                string containerType = context.Request["childContainer"].ToString();
                if (containerType == "3" && dtChildContainer.Rows.Count == 0)
                {
                    result.Result = false;
                    result.Message = "请选择子工序";
                    break;
                }
                DataTable dtStepCheckPoint = JsonConvert.DeserializeObject<DataTable>(context.Request["stepCheckPointData"].ToString());//检测项列表
                if (dtStepCheckPoint.Rows.Count == 0)
                {
                    result.Result = false;
                    result.Message = "请选择检测项";
                    break;
                }
                dic.Add("StepCheckPointID", "");
                string stepCheckPointIDs = string.Empty;
                dtStepCheckPoint.AsEnumerable().ToList().ForEach(p =>
                {
                    stepCheckPointIDs += string.Format("'{0}',", p["StepCheckPointID"].ToString());
                });
                stepCheckPointIDs = stepCheckPointIDs.TrimEnd(',');
                string sql = @"select 1 from stepcheckpointresult sr where sr.stepcheckpointid IN ({0})
                     and sr.workerid != '{1}' and sr.containerid = '{2}'";
                if (dtChildContainer.Rows.Count > 0)
                {
                    string childContainerIDs = string.Empty;//子序号ID
                    dtChildContainer.AsEnumerable().ToList().ForEach(p => { childContainerIDs += string.Format("'{0}',", p["containerID"].ToString()); });
                    childContainerIDs = childContainerIDs.TrimEnd(',');
                    sql += string.Format(" and sr.childcontainerid in ({0})", childContainerIDs);
                }
                if (DatabaseHelper.GetSingle(string.Format(sql, stepCheckPointIDs, m_UserInfo.EmployeeID.ToString(), containerID)) != null)
                {
                    result.Result = false;
                    result.Message = "存在其他工人录入";
                    break;
                }
                if (dtChildContainer.Rows.Count == 0) //没带子序号的数据保存
                {
                    foreach (DataRow item in dtStepCheckPoint.Rows)
                    {
                        dic["StepCheckPointID"] = item["StepCheckPointID"].ToString();
                        sql = string.Format("SELECT 1 FROM stepcheckpointresult sr WHERE sr.stepcheckpointid = '{0}' AND sr.containerid = '{1}'", dic["StepCheckPointID"], containerID);
                        int inputNum = int.Parse(item["inputNum"].ToString());//检测项的录入次数
                        int resNum = DatabaseHelper.Query_ReturnDatTable(sql).Rows.Count;//录入结果的次数
                        for (int i = resNum; i < inputNum; i++)
                        {
                            m_CheckPointObj.SaveCheckResultByWorker(dic);
                        }
                    }
                }
                else
                {
                    foreach (DataRow item in dtStepCheckPoint.Rows)
                    {
                        dic["StepCheckPointID"] = item["StepCheckPointID"].ToString();
                        foreach (DataRow itemCh in dtChildContainer.Rows)
                        {
                            dic["ChildContainerID"] = itemCh["ContainerID"].ToString();
                            sql = string.Format("SELECT 1 FROM stepcheckpointresult sr WHERE sr.stepcheckpointid = '{0}' AND sr.containerid = '{1}' AND sr.childcontainerid = '{2}'", dic["StepCheckPointID"], containerID, dic["ChildContainerID"]);
                            int inputNum = int.Parse(item["inputNum"].ToString());//检测项的录入次数
                            int resNum = DatabaseHelper.Query_ReturnDatTable(sql).Rows.Count;//录入结果的次数
                            for (int i = resNum; i < inputNum; i++)
                            {
                                m_CheckPointObj.SaveCheckResultByWorker(dic);
                            }
                        }
                    }
                }
                break;
            case "edit"://修改
                string stepCheckPointID = context.Request["stepCheckPointId"].ToString();//检测项ID
                dic.Add("StepCheckPointID", stepCheckPointID);
                DataTable dtCheckPointResult = new DataTable();//检测项结果
                dtCheckPointResult = JsonConvert.DeserializeObject<DataTable>(context.Request["checkPointResult"].ToString());
                foreach (DataRow item in dtCheckPointResult.Rows)
                {
                    dic["StepCheckPointResultID"] = item["StepCheckPointResultID"].ToString();
                    dic["UsingImgPath"] = usingImg;
                    m_CheckPointObj.SaveCheckResultByWorker(dic);
                }
                break;
            default:
                result.Result = false; result.Message = "未知操作";
                break;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 删除实测值结果
    /// </summary>
    /// <param name="context"></param>
    public void DeleteCheckPointResult(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "删除成功" };
        string deleType = context.Request["deleType"].ToString();
        DataTable dtCheckPointResult = JsonConvert.DeserializeObject<DataTable>(context.Request["checkPointResult"].ToString());
        switch (deleType)
        {
            case "1": //删除检验实测值
                foreach (DataRow item in dtCheckPointResult.Rows)
                {
                    result.Result = m_CheckPointObj.DeleteCheckResultById(item["StepCheckPointResultID"].ToString(), usingImg);
                }
                break;
            case "2"://删除工人实测值
                foreach (DataRow item in dtCheckPointResult.Rows)
                {
                    result.Result = m_CheckPointObj.DeleteWorkerResultById(item["StepCheckPointResultID"].ToString(), usingImg);
                }
                break;
            default:
                result.Result = false;
                result.Message = "未知参数";
                break;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 初始化实测值录入页面（报工）
    /// </summary>
    /// <param name="context"></param>
    public void InitCheckPointPageByReport(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable dtReportContainer = new DataTable();
        if (context.Session["PopupData"] != null)
        {
            dtReportContainer = (DataTable)context.Session["PopupData"];
        }
        else
        {
            string paramStr = context.Request["paramStr"].ToString();//获取加密字符串，解密后获取数据
            DataTable dtParam = new DataTable();
            string sql = string.Format(@"
                                 SELECT Distinct cci.containerid,cci.containername,cci.containertype,cci.productname,ws.workflowstepname,ws.workflowstepid,
                                 decode(cci.containertype,'2','批量加工','3','批量带子序号','7','单件加工','其他') containertypename,
                                 '' stepinfoid,'' stepno,'' stepInfoname
                                 FROM containercurrentinfo cci 
                                 --LEFT JOIN containerstepdispatch csd ON csd.containerid = cci.containerid AND csd.workflowstepid = '{0}' AND csd.isuse = 0
                                 LEFT JOIN workflowstep ws ON ws.workflowstepid = '{0}'
                                 WHERE cci.containerid = '{1}'
                                 {2}", "");
            StringBuilder newSql = new StringBuilder();
            for (int i = 0; i < dtParam.Rows.Count; i++)
            {
                if (i + 1 == dtParam.Rows.Count)
                {
                    newSql.AppendFormat(sql, dtParam.Rows[i][""].ToString(), "");
                }
                else
                {
                    newSql.AppendFormat(sql, dtParam.Rows[i][""].ToString(), " UNION ALL ");
                }
            }
            dtReportContainer = DatabaseHelper.Query_ReturnDatTable(newSql.ToString());
        }
        if (dtReportContainer.Rows.Count == 0)
        {
            result.Result = false;
            result.Message = "未查询到数据，请刷新报工页面";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (!dtReportContainer.Columns.Contains("StepInfoID"))
        {
            dtReportContainer.Columns.Add("StepInfoID");//如果没有工步，加一个空值，防止后续报错
            dtReportContainer.Columns.Add("StepInfoName");
        }
        foreach (DataColumn item in dtReportContainer.Columns)
        {
            item.ColumnName = item.ColumnName.ToUpper();
        }
        dtReportContainer.TableName = "dtReportContainer";
        result.DBDataSet.Tables.Add(dtReportContainer);
        //批次子序号
        if (dtReportContainer.Rows[0]["ContainerType"].ToString() == "3")
        {
            if (string.IsNullOrWhiteSpace(dtReportContainer.Rows[0]["StepInfoID"].ToString()))
            {
                DataTable dtChildContainer = m_CommonObj.GetContainerInfoByPerContianerID2(dtReportContainer.Rows[0]["ContainerID"].ToString());
                dtChildContainer.TableName = "dtChildContainer";
                result.DBDataSet.Tables.Add(dtChildContainer);
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 初始化检验实测值页面（检验）
    /// </summary>
    /// <param name="context"></param>
    public void InitCheckPointPageByCheck(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable dtSession = (DataTable)context.Session["PopupData"];
        if (dtSession.Rows.Count == 0)
        {
            result.Result = false;
            result.Message = "没有数据，请刷新页面";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (!dtSession.Columns.Contains("StepInfoID"))
        {
            dtSession.Columns.Add("StepInfoID");//如果没有工步，加一个空值，防止后续报错
            dtSession.Columns.Add("StepInfoName");
        }
        //-------------- add by longb 为了兼容多批次批量操作
        var type = context.Request["type"].ToString();
        var ContainerID = string.Empty;
        foreach (DataRow dr in dtSession.Rows)
        {
            ContainerID += "|" + dr["ContainerID"] + "|,";
        }
        DataRow rowContianer = dtSession.Rows[0];
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("ContainerID", type == "2" ? ContainerID.TrimEnd(',').TrimEnd('|').TrimStart('|').Replace("|", "'") : rowContianer["ContainerID"].ToString());
        //-------------------------------------
        para.Add("WorkflowStepID", rowContianer["WorkflowStepID"].ToString());
        //如果包含有工步，查询工步
        if (!string.IsNullOrWhiteSpace(rowContianer["StepInfoID"].ToString()))
        {
            para.Add("StepInfoID", rowContianer["StepInfoID"].ToString());
        }
        DataTable dtReportContainer = m_CheckPointObj.GetWorkreportInfoByContainer(para);//报工批次
        dtReportContainer.TableName = "dtReportContainer";
        result.DBDataSet.Tables.Add(dtReportContainer);
        //批次子序号
        if (rowContianer["ContainerType"].ToString() == "3")
        {
            if (string.IsNullOrWhiteSpace(rowContianer["StepInfoID"].ToString())) //如果包含工步，则不显示子序号
            {
                DataTable dtChildContainer = m_CommonObj.GetContainerInfoByPerContianerID2(rowContianer["ContainerID"].ToString());
                dtChildContainer.TableName = "dtChildContainer";
                result.DBDataSet.Tables.Add(dtChildContainer);
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取检测项列表数
    /// </summary>
    /// <param name="context"></param>
    public void GetStepCheckPointData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        Dictionary<string, string> oQuery = new Dictionary<string, string>();
        //oQuery.Add("ProductID", context.Request["productID"].ToString());
        oQuery.Add("ContainerID", context.Request["containerID"].ToString());
        oQuery.Add("StepID", context.Request["workFlowStepId"].ToString());
        oQuery.Add("ContainerStepWorkReportID", context.Request["containerStepWorkReportID"].ToString());
        oQuery.Add("StepInfoID", context.Request["stepInfoID"].ToString());
        int pageSize = int.Parse(context.Request["pageSize"].ToString());
        int pageIndex = int.Parse(context.Request["pageIndex"].ToString());
        //result = m_CheckPointObj.GetInputStepCheckPointList(oQuery); //获取该工步下的检测项（老页面的数据获取）
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(@"SELECT sp.stepcheckpointid,sp.checktype,nvl(sp.checkpointnote,'') checkpointnote,sp.inputnum,sp.basevalue,sp.ceilfloat,sp.floorfloat,sp.checkmethod,
                            nvl(sp.checkpointnotedis,'') checkpointnotedis,nvl(sp.checkpointnotedis_b,'') checkpointnotedis_b,
                            sp.keycheck,sp.name,sp.DrawingRequire,sp.DrawingRequireDis,nvl(sp.DrawingRequireDis_b,'') DrawingRequireDis_b,sp.BubbleNumber,
                            DECODE(sp.CHECKTYPE, '3', '设计特性', '4', '过程参数', CHECKTYPE) CHECKTYPENAME,
                            DECODE(sp.KEYCHECK, '1', '是', '0', '否', KEYCHECK) KEYCHECKNAME,
                            DECODE(sp.MEOPCHECK, '1', '是', '0', '否', MEOPCHECK) MEOPCHECKNAME,
                            DECODE(sp.QUALITYCHECK, '1', '是', '0', '否', QUALITYCHECK) QUALITYCHECKNAME,
                            DECODE(sp.TCCHECKPOINTNOTE, NULL, '否', '是') ISTCM,
                            (SELECT COUNT(1) FROM stepcheckpointresult spr WHERE spr.stepcheckpointid = sp.stepcheckpointid AND spr.containerid = '{0}'{1}) inputcount 
                            FROM stepcheckpoint sp", oQuery["ContainerID"], !string.IsNullOrWhiteSpace(oQuery["ContainerStepWorkReportID"]) ? string.Format(" AND spr.containerstepworkreportid = '{0}'", oQuery["ContainerStepWorkReportID"]) : "");//如果报工ID 不为空，则统计到报工级
        sql.AppendFormat(" WHERE sp.workflowstepid = '{0}' ", oQuery["StepID"]);
        if (!string.IsNullOrWhiteSpace(oQuery["StepInfoID"]))
        {
            sql.AppendFormat(" AND sp.stepinfoid = '{0}'", oQuery["StepInfoID"]);
        }
        //        sql.AppendLine(@" GROUP BY sp.stepcheckpointid,sp.checktype,sp.checkpointnote,sp.checkpointnotedis,sp.checkpointnotedis_b,sp.keycheck,sp.name,sp.bubblenumber,
        //                           sp.checkpointnotedis,sp.drawingrequiredis,sp.qualitycheck,sp.meopcheck,sp.tccheckpointnote,sp.DrawingRequireDis,sp.DrawingRequireDis_b,sp.DrawingRequire");
        uMESPagingDataDTO page = new uMESPagingDataDTO() { PageSize = pageSize, CurrentPageIndex = pageIndex, strSQL = sql.ToString() };
        result = DatabaseHelper.RunProcedureForPage(page);
        //result.RowCount = result.DBTable.Rows.Count.ToString();//总数
        //result.DBTable = result.DBTable.AsEnumerable().Skip(pageSize * (pageIndex - 1)).Take(pageSize).CopyToDataTable();//分页
        result.DBTable = UpdatePointDis(result.DBTable);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    private DataTable UpdatePointDis(DataTable dtPoint)
    {
        foreach (DataRow item in dtPoint.Rows)
        {
            if (string.IsNullOrWhiteSpace(item["Checkpointnote"].ToString()))
            {
                continue;
            }
            ExcuteEntity exuteEntity = new ExcuteEntity("stepcheckpoint", ExcuteEntity.ExcuteTypeEnum.update);
            exuteEntity.WhereFileds = new List<FieldEntity> { new FieldEntity("stepcheckpointid", item["stepcheckpointid"].ToString(), FieldEntity.FieldTypeEnum.Str) };
            List<FieldEntity> excuteFieldList = new List<FieldEntity>();
            if (string.IsNullOrWhiteSpace(item["CheckpointnoteDis"].ToString()))
            {
                item["CheckpointnoteDis"] = m_CheckPointObj.ConvertTohtml(item["Checkpointnote"].ToString(), usingImg, isUseIP);
                excuteFieldList.Add(new FieldEntity("CheckpointnoteDis", item["CheckpointnoteDis"].ToString(), FieldEntity.FieldTypeEnum.Str));
            }
            if (!string.IsNullOrWhiteSpace(item["DrawingRequire"].ToString()) && string.IsNullOrWhiteSpace(item["DrawingRequireDis"].ToString()))
            {
                item["DrawingRequireDis"] = m_CheckPointObj.ConvertTohtml(item["DrawingRequire"].ToString(), usingImg, isUseIP);
                excuteFieldList.Add(new FieldEntity("DrawingRequireDis", item["DrawingRequireDis"].ToString(), FieldEntity.FieldTypeEnum.Str));
            }
            //更新数据库数据
            if (excuteFieldList.Count > 0)
            {
                exuteEntity.ExcuteFileds = excuteFieldList;
                DatabaseAccess.DBUtility.DatabaseHelper.ExecuteDataByEntity(exuteEntity);
            }
        }
        dtPoint.AcceptChanges();
        return dtPoint;
    }

    /// <summary>
    /// 获取检测项结果列表
    /// </summary>
    /// <param name="context"></param>
    public void GetStepCheckPointResult(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable dtChildContainer = JsonConvert.DeserializeObject<DataTable>(context.Request["childContainer"].ToString());
        string childContainerIDs = string.Empty;//子序号ID
        if (dtChildContainer.Rows.Count > 0)
        {
            dtChildContainer.AsEnumerable().ToList().ForEach(p => { childContainerIDs += string.Format("'{0}',", p["containerID"].ToString()); });
        }
        string stepCheckPointID = context.Request["stepCheckPointId"].ToString();//检测项ID
        string containerID = context.Request["containerId"].ToString();//批次ID
        string containerStepWorkReportID = context.Request["containerStepWorkReportID"].ToString();//报工ID
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(@"SELECT spr.checkpointresultnotedis,spr.workcheckpointresultnotedis,spr.stepcheckpointresultid,spr.containerstepworkreportid,sp.basevalue,sp.floorfloat,sp.ceilfloat,
                            spr.checkpointresultnotedis_b,spr.workcheckpointresultnotedis_b,nvl(spr.spcstatus,0) spcstatus,DECODE(spr.spcstatus,1,'异常','') spcstatusname,
                            e.fullname worker,em.fullname checker,c.containername childcontainername,spr.createdate,spr.checkdate,NVL(spr.workresultdocpath,'') workresultdocpath,
                            NVL(spr.checkresultdocpath,'') checkresultdocpath,'' checkresultdocname,'' workresultdocname,'' workresultOver,'' checkresultOver
                             FROM stepcheckpointresult spr
                            LEFT JOIN stepcheckpoint sp ON sp.stepcheckpointid = spr.stepcheckpointid
                            LEFT JOIN employee e ON e.employeeid = spr.workerid
                            LEFT JOIN employee em ON em.employeeid = spr.checkerid
                            LEFT JOIN container c ON c.containerid = spr.childcontainerid AND c.status =1
                            WHERE spr.stepcheckpointid = '{0}' AND spr.containerid = '{1}'", stepCheckPointID, containerID);
        if (!string.IsNullOrWhiteSpace(childContainerIDs))
        {
            childContainerIDs = childContainerIDs.TrimEnd(',');
            sql.AppendFormat(" AND c.containerid in ({0})", childContainerIDs);
        }
        if (!string.IsNullOrWhiteSpace(containerStepWorkReportID))//报工ID 不为空
        {
            sql.AppendFormat(" AND spr.containerstepworkreportid = '{0}'", containerStepWorkReportID);
        }
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(sql.ToString());
        foreach (DataRow item in result.DBTable.Rows)
        {
            if (!string.IsNullOrWhiteSpace(item["workresultdocpath"].ToString()))
            {
                item["workresultdocname"] = Path.GetFileName(item["workresultdocpath"].ToString());
                item["workresultdocpath"] = string.Format("http://{0}{1}{2}", context.Request.Url.Host, context.Request.ApplicationPath, item["workresultdocpath"].ToString());
            }
            if (!string.IsNullOrWhiteSpace(item["checkresultdocpath"].ToString()))
            {
                item["checkresultdocname"] = Path.GetFileName(item["checkresultdocpath"].ToString());
                item["checkresultdocpath"] = string.Format("http://{0}{1}{2}", context.Request.Url.Host, context.Request.ApplicationPath, item["checkresultdocpath"].ToString());
            }
            if (IsOverproofResult(item["basevalue"].ToString(),item["floorfloat"].ToString(),item["ceilfloat"].ToString(),item["workcheckpointresultnotedis"].ToString()))
            {
                item["workresultOver"] = "是";
            }
            if (IsOverproofResult(item["basevalue"].ToString(), item["floorfloat"].ToString(), item["ceilfloat"].ToString(), item["checkpointresultnotedis"].ToString()))
            {
                item["checkresultOver"] = "是";
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }


    public String GetCode(HttpContext context)
    {
        String strHtmlCode, strHtml, strHtmlTemp;
        try
        {
            DataTable dtImage = new DataTable();
            int i, intStartFlag, intEndFlag;
            dtImage = (DataTable)context.Session["dtImage"];

            strHtml = context.Request["strCode"].ToString();//ftbFinalHtml.Text.Trim();
            strHtmlCode = strHtml;

            intStartFlag = strHtmlCode.IndexOf("<img");
            if (intStartFlag == -1)
            {
                intStartFlag = strHtmlCode.IndexOf("<IMG");
            }
            if (intStartFlag > -1)
            {
                intEndFlag = strHtmlCode.IndexOf(">", intStartFlag);
                ;
            }
            else
            {
                intEndFlag = -1;
            }

            if (dtImage != null)
            {
                if (dtImage.Rows.Count > 0)
                {
                    while (intStartFlag > -1)
                    {
                        strHtmlTemp = strHtmlCode.Substring(intStartFlag, intEndFlag - intStartFlag + 1);
                        for (i = 0; i <= dtImage.Rows.Count - 1; i++)
                        {
                            if (strHtmlTemp.IndexOf(@"/" + dtImage.Rows[i][0]) > -1)
                            {
                                strHtmlCode = strHtmlCode.Replace(strHtmlTemp, (String)dtImage.Rows[i][1]);
                                break;
                            }

                        }

                        intStartFlag = strHtmlCode.IndexOf("<img", intStartFlag + 1);
                        if (intStartFlag == -1)
                        {
                            intStartFlag = strHtmlCode.IndexOf("<IMG", intStartFlag + 1);
                        }
                        if (intStartFlag > -1)
                        {
                            intEndFlag = strHtmlCode.IndexOf(">", intStartFlag + 1);
                            ;
                        }
                        else
                        {
                            intEndFlag = -1;
                        }
                        //intEndFlag = strHtmlCode.IndexOf(">", intStartFlag + 1);
                    }

                }

            }

            return strHtmlCode;
        }
        catch (Exception myError)
        {
            return "";
        }
    }

    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="filePath"></param>
    private void DeleteUploadedFile(string filePath)
    {
        if (File.Exists(filePath))
        {
            FileInfo fileinfo = new FileInfo(filePath);
            fileinfo.Attributes = FileAttributes.Normal;
            File.Delete(filePath);
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}
